package com.qd.system.importexcel.station;

import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.cdqidi.dto.BatchResult;
import com.cdqidi.excel.domain.ExcelRowMsg;
import com.cdqidi.excel.domain.ImportErr;
import com.cdqidi.excel.util.ExcelUtil;
import com.cdqidi.exception.ExcelOperatorException;
import com.cdqidi.util.ValidatorUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.qd.common.sys.domain.entity.station.StationOrgDTO;
import com.qd.system.model.StationOrg;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.org.OrgService;
import com.qd.system.service.station.StationOrgService;
import com.qd.system.service.station.StationSetService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintViolationException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * 岗位组织,excel导入处理类
 *
 * @author sjk
 */
@Slf4j
@RequiredArgsConstructor
public class StationOrgImportHandler {

    private final StationOrgService stationOrgService;
    private final ValidatorUtil validatorUtil;
    private final List<ImportErr> errorList;

    private final OrgService orgService;

    private final StationSetService stationSetService;

    private final LocalDateTime now = LocalDateTime.now();

    /**
     * 处理具体导入
     *
     * @param rowList excel行数据集合，默认为1000行
     * @param results 异常信息存储
     */
    public void process(List<ExcelRowMsg<StationOrgDTO>> rowList, List<BatchResult> results) {
        final List<StationOrgDTO> stationOrgList = rowList.stream().map(ExcelRowMsg::getRowData).collect(toList());
        final List<String> orgIds = stationOrgList.stream().map(StationOrgDTO::getOrgId).filter(StringUtils::hasLength).collect(toList());
        final List<String> stationIds = stationOrgList.stream().map(StationOrgDTO::getStationId).filter(StringUtils::hasLength).collect(toList());
        final List<String> existsOrgIds = orgService.getBaseMapper().getIds(orgIds);
        final List<String> existsStationIds = stationSetService.getBaseMapper().getIds(stationIds);
        final List<String> existsOrgStationIds = existsOrgStationIds(existsStationIds, existsOrgIds);
        final List<String> existsIds = existsIds(stationOrgList);
        final int size = rowList.size();
        try {
            for (ExcelRowMsg<StationOrgDTO> excelRowMsg : rowList) {
                final List<String> errors = new ArrayList<>();
                final StationOrgDTO stationOrgDTO = excelRowMsg.getRowData();
                final ReadRowHolder readRowHolder = excelRowMsg.getReadRowHolder();
                if (null == stationOrgDTO.getAddTime()) {
                    stationOrgDTO.setAddTime(now);
                }
                importValidate(stationOrgDTO, errors);
                importBaseColumn(stationOrgDTO, existsOrgIds, existsStationIds, existsOrgStationIds, errors);
                if (!errors.isEmpty()) {
                    errorList.add(ExcelUtil.buildError(readRowHolder, errors));
                }
            }
            if (!errorList.isEmpty()) {
                throw new ExcelOperatorException(errorList);
            } else {
                final List<StationOrg> addStationOrgList = new ArrayList<>(size);
                final List<StationOrg> updateStationOrgList = new ArrayList<>(size);
                doProcessDictData(existsIds, stationOrgList, addStationOrgList, updateStationOrgList);
                BatchResult.buildBatchResult(results, addStationOrgList.size(), updateStationOrgList.size());
                addStationOrgList.clear();
                updateStationOrgList.clear();
            }
        } finally {
            stationOrgList.clear();
            existsIds.clear();
        }
    }

    private List<String> existsOrgStationIds(List<String> stationIds, List<String> orgIds) {
        if (stationIds.isEmpty() || orgIds.isEmpty()) {
            return Collections.emptyList();
        }
        return stationOrgService.getBaseMapper().getOrgStationIds(orgIds, stationIds);
    }

    private void importBaseColumn(StationOrgDTO stationOrgDTO, List<String> existsOrgIds, List<String> existsStationIds, List<String> existsOrgStationIds, List<String> errors) {
        boolean isNotCheck = false;
        if (!MbUtil.isExistInCollection(existsOrgIds, stationOrgDTO.getOrgId())) {
            errors.add("机构ID不存在[" + stationOrgDTO.getOrgId() + "]");
            isNotCheck = true;
        }
        if (!MbUtil.isExistInCollection(existsStationIds, stationOrgDTO.getStationId())) {
            errors.add("职责ID不存在[" + stationOrgDTO.getStationId() + "]");
            isNotCheck = true;
        }
        if (isNotCheck) {
            return;
        }
        if (MbUtil.isExistInCollection(existsOrgStationIds, stationOrgDTO.getStationId())) {
            errors.add("岗位和机构关系已经分配[" + stationOrgDTO.getStationId() + "|" + stationOrgDTO.getOrgId() + "]");
        }

    }

    /**
     * 保存数据
     *
     * @param existsIds            已经存在的数据库主键
     * @param stationOrgList       excel行数据集合
     * @param addStationOrgList    添加集合
     * @param updateStationOrgList 更新集合
     */
    private void doProcessDictData(List<String> existsIds, List<StationOrgDTO> stationOrgList, List<StationOrg> addStationOrgList, List<StationOrg> updateStationOrgList) {
        stationOrgList.forEach(stationOrgDTO -> {
            final StationOrg stationOrg = stationOrgService.dtoToModel(stationOrgDTO);
            stationOrgService.clearCache(stationOrg);
            if (MbUtil.isExistInCollection(existsIds, stationOrgDTO.getOrgStationId())) {
                updateStationOrgList.add(stationOrg);
            } else {
                addStationOrgList.add(stationOrg);
            }
        });
        if (!addStationOrgList.isEmpty()) {
            stationOrgService.saveBatch(addStationOrgList);
        }
        if (!updateStationOrgList.isEmpty()) {
            stationOrgService.updateBatchIds(updateStationOrgList);
        }
    }

    /**
     * 获得主键存在的集合
     *
     * @param stationOrgList excel行数据集合
     * @return 主键集合
     */
    private List<String> existsIds(List<StationOrgDTO> stationOrgList) {
        final List<String> ids = stationOrgList.stream().map(StationOrgDTO::getOrgStationId).collect(toList());
        final List<String> existsIds = stationOrgService.getBaseMapper().getIds(ids);
        ids.clear();
        return existsIds;
    }

    /**
     * 导入实体验证
     *
     * @param stationOrgDTO 单个excel行数据
     * @param errors        异常信息存储
     */
    private void importValidate(StationOrgDTO stationOrgDTO, List<String> errors) {
        if (errors.isEmpty()) {
            try {
                validatorUtil.checkValid(stationOrgDTO, DefaultGroup.class);
            } catch (ConstraintViolationException e) {
                errors.addAll(validatorUtil.getValidationError(e));
            }
        }
    }
}